package post_to_in_pkg.node;
import post_to_in_pkg.GlobalConfig;

import java.util.ArrayList;

public class Blocks extends Node{
	ArrayList<Node> children;
	private boolean addindent=true;
	public String code=""; //no precedent code ;

	public Blocks(ArrayList<Node> blocks) {
		children=blocks;
	}
	

	
	public Blocks(Node block) {
		children=new ArrayList<Node>();
		children.add(block);
	}
	
	//no children block 
	public Blocks() {
		children=null;
	}

	public void cutLeaf(int index) {
		children.remove(index);
	}
	
	public void born(Node lastSibling) {
		if(children==null) children=new ArrayList<Node>();
		children.add(lastSibling);
	}
	
	public String toString() {
		String s="\n";
		for(Node iter: children) {
			if(iter!=null)
				s=s.concat(iter.toString());s+="\n";
		}
		return s;
	}
	
	public int CountBlock() {
		return children.size();
	}
	
	public boolean isReturnVoid() {
		return true;
	}
	
	public boolean isTempNode(){
		return false;
	}
	
	public void bornToFirst(Node node) {
		if(children==null) children=new ArrayList<Node>();
		children.add(0, node);
	}
	
	public Node splitLast() {
		Node node=children.get(children.size()-1);
		children.remove(children.size()-1);
		return node;
	}
	
	public boolean hasNoChild() {
		return children==null||children.isEmpty();
	}
	public static final Blocks NullBlock=new Blocks();


	@Override
	public boolean hasChild() {
		// TODO Auto-generated method stub
		if(children==null||children.isEmpty())
			return false;
		return true;
	}

	//@deprecated
	// public void printChild(StringBuffer content) {
	// 	// TODO Auto-generated method stub
	// 	StringBuffer blockstr=new StringBuffer(),
	// 			childstr=new StringBuffer();
	// 	if(hasChild()) {
	// 		for(Node child:children) {
	// 			child.printChild(childstr);		
	// 			blockstr.append(childstr);
	// 			childstr.setLength(0); //clear buffer
	// 		}
	// 		content=content.insert(0, blockstr);
	// 	}
	// 	addIndent(content);
	// }

	public void setIndent(boolean set) {
		addindent=set;
	}

	 //@Modified
	 public void addIndent() {
	 	if(addindent) {
			StringBuffer content = new StringBuffer();
			content.append(code);
			content.insert(0, '\t');
			int next = content.indexOf("\n");
			while (next != -1 && next + 1 < content.length()) {
				content.insert(next + 1, '\t');
				next = content.indexOf("\n", next + 1);
			}
			code = content.toString();
	 	}
	 }
	
	public String[] generateCodes(){
		String[] blockCode=new String[2];
		if(hasChild()) {
			int size = CountBlock();
			String[][] codesVector=new String[size][2];
			for(int i=0; i<size;i++){
				codesVector[i]=children.get(i).generateCodes();
			}
			//concat them
			for(int i=0; i<size;i++){
				code=code+"\n"+codesVector[i][0]+"\n"+codesVector[i][1];
			}
		}
		addIndent();
		blockCode[1]=code;
		return blockCode;
	}
}
